package cn.jsu.oj.judgment.process;

import cn.jsu.oj.judgment.config.ResourceConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerDomainSocketChannel;
import io.netty.channel.unix.DomainSocketAddress;

import io.netty.channel.unix.UnixChannelOption;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


@Slf4j
@Component("judgeUnixServer")
public class JudgeUnixServer {

    private static final String socketFile = ResourceConfig.getConfigString("judge.socket.fileName");
    private ServerBootstrap serverBootstrap;
    private EpollEventLoopGroup boss;
    private EpollEventLoopGroup  worker;
    public void init() {
        this.boss = new EpollEventLoopGroup();
        log.info("?????????????");
        this.worker = new EpollEventLoopGroup();
        this.serverBootstrap = new ServerBootstrap();
        JudgeUnixDomainChannelInit channelInit = new JudgeUnixDomainChannelInit();
        this.serverBootstrap.group(this.boss,this.worker)
                .channel(EpollServerDomainSocketChannel.class)
                .option(UnixChannelOption.SO_BACKLOG,128)
//                .childOption(UnixChannelOption.SO_REUSEADDR,true)
                .childHandler(channelInit);
    }

    public void start() {
        init();
        log.info("..........判题机Unix套接域正在启动.........");
        try {
            ChannelFuture channelFuture = this.serverBootstrap.bind(new DomainSocketAddress(socketFile)).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {

        }
        finally {
            try {
                this.boss.shutdownGracefully().sync();
                this.worker.shutdownGracefully().sync();
            }
             catch (InterruptedException e) {
                 log.error(e.getLocalizedMessage(),e);
            }
        }

    }


}
